/* eslint-disable eol-last */
import axios from "axios";
import { Toast } from "vant";
import store from "@/store/index";
const baseURL = process.env.VUE_APP_BASE_API;

// 创建axios实例
/***
 * requestConfig 对请求特殊化处理的对象，包含errflag,isLoading,timeout属性
 * 属性errFlag 请求出错后是否拦截预配置的错误弹窗，进行特殊处理
 * 属性isLoading 请求是否有loading
 * 属性timeout 请求超时时间
 *
 * ***/
const httpRequest = function (
    requestConfig = {
        errFlag: false,
        isLoading: true,
        timeout: 3000000,
    }
) {
    const service = axios.create({
        baseURL: baseURL,
        timeout: requestConfig.timeout,
    });
    // request拦截器  添加请求头
    service.interceptors.request.use(
        (config) => {
            if (requestConfig.isLoading === true) {
                // 存在loading标记时弹出loading
                showFullScreenLoading();
            }
            const token = sessionStorage.getItem("token");
            if (token) {
                config.headers.Authorization = token;
            } else {
                // config.headers.Authorization = ''
            }
            return config;
        },
        (error) => {
            if (requestConfig.isLoading === true) {
                tryHideFullScreenLoading();
            }
            return Promise.error(error);
        }
    );

    // response 拦截器
    service.interceptors.response.use(
        // 请求成功
        (res) => {
            // debugger
            if (requestConfig.isLoading === true) {
                tryHideFullScreenLoading();
            }
            const { data } = res;
            let resultConfig = res.config;
            let resultCode = res.status;
            // let reqResult = data.success;
            let message = data.status.msg;

            if (resultConfig.responseType === "arraybuffer") {
                return Promise.resolve(data);
            } else if (resultCode === 200) {
                return Promise.resolve(data);
            } else if (resultCode === 403) {
                Toast({
                    showClose: true,
                    message: "登录超时,请重新登录！",
                    duration: 1000,
                    type: "error",
                    onClose: function () {
                        window.localStorage.clear();
                        window.sessionStorage.clear();
                        store.commit("Clear_User");
                        let url = location.href;
                        if (url && url.indexOf("/ssoLogin") !== -1) {
                            url = url.replace("/ssoLogin", "/login");
                            location.href = url;
                        }
                        location.reload();
                    },
                });
                return Promise.reject(data);
            } else {
                if (requestConfig.errFlag) {
                    // 当存在错误标记时，直接抛出，在请求中特殊处理该数据
                    return Promise.reject(data);
                } else {
                    Toast({
                        showClose: true,
                        message: message,
                        duration: 5000,
                        type: "error",
                    });
                    return Promise.reject(data);
                }
            }
        },
        // 请求失败
        (error) => {
            if (requestConfig.isLoading === true) {
                tryHideFullScreenLoading();
            }
            // debugger
            if (!window.navigator.onLine) {
                Toast.fail("断开连接，请您检查网络");
                return Promise.reject(error);
            } else if (error.message.includes("timeout")) {
                // debugger //判断请求异常信息中是否含有超时timeout字符串
                Toast.fail("网络超时");
                return Promise.reject(error);
            } else if (error.message.includes("Network Error")) {
                Toast.fail("网络错误");
                return Promise.reject(error);
            } else {
                Toast.fail(String(error));
                return Promise.reject(error);
            }
        }
    );
    return service;
};

// 全局loading
let loading;

function startLoading() {
    // loading = Loading.service({
    //     lock: true,
    //     text: "加载中",
    //     background: "rgba(255, 255, 255, 0.7)",
    //     spinner: "newloading",
    // });
}
// 串行请求loading延迟关闭，处理loading闪烁问题
const tryCloseLoading = () => {
    if (needLoadingRequestCount === 0) {
        // loading.close();
    }
};
// 那么 showFullScreenLoading() tryHideFullScreenLoading() 要干的事儿就是将同一时刻的请求合并。
// 声明一个变量 needLoadingRequestCount，每次调用showFullScreenLoading方法 needLoadingRequestCount + 1。
// 调用tryHideFullScreenLoading()方法，needLoadingRequestCount - 1。needLoadingRequestCount为 0 时，结束 loading。
let needLoadingRequestCount = 0;
function showFullScreenLoading(text) {
    if (needLoadingRequestCount === 0) {
        startLoading(text);
    }
    needLoadingRequestCount++;
}

function tryHideFullScreenLoading() {
    if (needLoadingRequestCount <= 0) return;
    needLoadingRequestCount--;
    if (needLoadingRequestCount === 0) {
        // endLoading()
        setTimeout(() => {
            tryCloseLoading();
        }, 300);
    }
}
export default httpRequest;
